package com.i2works.smartluolong.utils.common;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Base64;

/**
 * 文件与base64字符之间的互转工具类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/5/28 10:32
 */

public class FileBase64ConvertUitl {

    /**
     * 将base64转换成上传文件
     */
    public static MultipartFile base64ToMultipart(String base64) {
            String[] baseStrs = base64.split(",");
            byte[] b = Base64.getDecoder().decode(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
    }

    /**
     * 将文件转成base64 字符串
     */

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.getEncoder().encodeToString(buffer);

    }

    /**
     * 将base64字符解码保存文件
     */

    public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
        byte[] buffer = Base64.getDecoder().decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();

    }

    /**
     * 将base64字符保存文本文件
     */

    public static void toFile(String base64Code, String targetPath) throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }



}
